package main

import (
	"io/ioutil"
	"os"

	pathpkg "path"

	"github.com/bitly/go-simplejson"
)

type config struct {
	//modules      []string
	//net_check    *simplejson.Json
	//ping_ips     string
	prome_addr   string
	log_file     string
	watcher_conf string
	interval     int64
	tags         map[string]string
}

func ReadConfig(fn string) (js *simplejson.Json) {
	f, err := os.Stat(fn)
	checkErr(err, "configjson stat error!")
	if f.IsDir() {
		log.Error("not a file!")
		os.Exit(2)
	}
	b, err := ioutil.ReadFile(fn)
	checkErr(err, "read configjson error!")
	js, err = simplejson.NewJson(b)
	checkErr(err, "change to json error!")
	return js
}

func ReadDir(fn string, conf *config) {
	info, err := os.Stat(fn)
	checkErr(err, "configfile stat error!")
	if !info.IsDir() {
		log.Error("not a directory!")
		os.Exit(2)
	}
	files, err := ioutil.ReadDir(fn)
	checkErr(err, "read configfile error!")
	for _, f := range files {
		if f.Name() == "mas.json" {
			p := pathpkg.Join(fn, f.Name())
			js := ReadConfig(p)
			//conf.modules = js.Get("modules").MustStringArray()
			//conf.net_check = js.Get("net_check")
			//conf.ping_ips = js.Get("ping_ips").MustString()
			conf.interval = js.Get("interval").MustInt64()
			conf.log_file = js.Get("log_file").MustString()
			conf.prome_addr = js.Get("prome_addr").MustString()
			tags := js.Get("tags").MustMap()
			if conf.tags == nil {
				conf.tags = make(map[string]string)
			}
			for k, v := range tags {
				conf.tags[k] = v.(string)
			}
			conf.watcher_conf = fn
		}
	}
}
